/**
 * 鼠标跟随文字
 * @directive 默认方式：v-tooltip，如 `<div v-tooltip :tips='文字内容'></div>`
 */
export function mouseTooltipDirective(app) {
    let isShow = false
    let showTxt = ''
    let vcTooltipDom
    app.directive('tooltip', {
        mounted(el, binding) {
            const {isMove, flowText} = binding.value
            isShow = isMove
            showTxt = flowText
            vcTooltipDom = document.createElement('div')
            vcTooltipDom.style.cssText = `
                  position:absolute;
                  font-size: 14px;
                  color: #333;
                  padding: 4px 10px;
                  border: 1px solid #ccc;
                  background: #f5f5f5;
                  z-index:1000`
            // 设置id方便寻找
            vcTooltipDom.setAttribute('id', 'vc-tooltip')
            // 将浮动元素插入到body中
            document.body.appendChild(vcTooltipDom)

            function mouseEnter(e) {
                if (isShow && showTxt) {
                    // 鼠标移入时，将浮动元素显示
                    vcTooltipDom.style.display = 'block'
                    vcTooltipDom.style.top = `${e.clientY - 30}px`
                    vcTooltipDom.style.left = `${e.clientX + 10}px`
                    // 浮层中的文字 通过属性值传递动态的显示文案
                    vcTooltipDom.innerHTML = showTxt
                }
            }

            // 鼠标移动时，动态修改浮动元素的位置属性
            function mouseMove(e) {
                if (!vcTooltipDom) return
                if (isShow && showTxt) {
                    vcTooltipDom.style.display = 'block'
                    vcTooltipDom.style.top = `${e.clientY - 30}px`
                    vcTooltipDom.style.left = `${e.clientX + 10}px`
                }
            }

            function mouseLeave() {
                if (!vcTooltipDom) return
                // 鼠标移出时将浮层元素隐藏
                vcTooltipDom.style.display = 'none'
            }

            el.addEventListener('mouseenter', mouseEnter)
            el.addEventListener('mousemove', mouseMove)
            el.addEventListener('mouseleave', mouseLeave)

            // 方便更新卸载使用
            el.__mouseEnter__ = mouseEnter
            el.__mouseMove__ = mouseMove
            el.__mouseLeave__ = mouseLeave
        },
        beforeUpdate(el, binding) {
            const {isMove, flowText} = binding.value
            isShow = isMove
            showTxt = flowText
            if (!vcTooltipDom) return
            vcTooltipDom.innerHTML = showTxt
            if (!isShow) {
                vcTooltipDom.style.display = 'none'
            }
        },
        beforeUnmount(el) {
            // 避免重复开销，卸载所有的监听
            // 解决问题：多次创建新的实例 =》 监听不取消 =》 同时存在多个无用的监听，导致页面卡顿
            el.removeEventListener('mouseenter', el.__mouseEnter__)
            el.removeEventListener('mousemove', el.__mouseMove__)
            el.removeEventListener('mouseleave', el.__mouseLeave__)
        }
    })
}
